/**
 * 将整个项目copy到另一个目录
 */

const fs = require('fs');
const path = require('path');

const { info } = console;
/**
 * 得到上一级文件夹为开发目录
 */
const devDir = path.resolve(__dirname, '../')

/**
 * 将开发目录的所有文件拷贝到另一个目录
 * 除了.git和.idea之外
 */

/**
 * 这个promisify和util.js中的不同
 * @param {function} call 
 * @returns 
 */
async function promisify(call) {
    return new Promise(resolve => {
        try {
            call(resolve);
        } catch (e) {
            resolve([, e]);
        }
    });;
}

/**
 * @param {String} p 
 * @returns 1:目录,2:文件
 */
async function isFile(p) {
    return await promisify(resolve => {
        fs.stat(p, (err, stats) => {
            if (err) {
                resolve([, err]);
            } else if (stats.isDirectory()) {
                resolve([1]);
            } else if (stats.isFile()) {
                resolve([2]);
            }
        });
    });
}

/**
 * 
 * @param {String} dir 
 * @param {string[]} excludes 
 * @param {function} callback 
 * @returns 
 */
async function travelDir(dir, excludes, callback) {
    if (excludes.indexOf(dir) > -1) return;
    /**
     * 做一个简单的验证,不是目录直接返回
     */
    const [flag] = await isFile(dir);
    if (flag !== 1) return false;

    const [files, err] = await promisify(resolve => {
        fs.readdir(dir, function (err, files) {
            resolve([files, err]);
        });
    })
    if (err) throw err;

    for (let i = 0, l = files.length; i < l; i++) {
        const file = files[i];
        var filedir = path.join(dir, file);
        const [flag, err] = await isFile(filedir);
        if (err) throw err;
        if (flag === 1) {
            //按照文件名顺序遍历
            const res = await travelDir(filedir, excludes, callback);
            if (res === false) return false;
        } else if (flag === 2) {
            callback(filedir);
        }
    }
}

const excludes = [
    path.join(devDir, '.git'),
    path.join(devDir, '.idea'),
    path.join(devDir, 'node_modules'),
];

const targetDevSpace = 'E:\\gitee\\mxDev';


function confirmDir(filePath) {
    const dirPath = path.dirname(filePath);
    if (!fs.existsSync(dirPath)) {
        const ss = dirPath.split('\\');
        let dir = ss.shift();
        ss.forEach(s => {
            dir += '\\' + s;
            !fs.existsSync(dir) && fs.mkdirSync(dir);
        });
    }
}


(async () => {
    const ps = [];
    //遍历所有文件夹
    await travelDir(devDir, excludes, p => {
        ps.push(path.relative(devDir, p));
    });

    for (let i = 0, l = ps.length; i < l; i++) {
        const p = ps[i];
        const targetP = path.join(targetDevSpace, p);
        confirmDir(targetP);

        const sourceP = path.join(devDir, p);
        //字节方式拷贝
        fs.writeFileSync(targetP, fs.readFileSync(sourceP));
        info(sourceP,'==>',targetP);
    }
})();